<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 基本信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillId_FormItem" prop="Entity.BillId">
								<template #label>
									<WtmLabelTooltip label="采购申请单" tooltip="关联的采购申请单主表" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.BillId" clearable class="width100" :disabled="true">
									<el-option v-for="item in stateData.AllSysPurchaseRequestBills" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_PurchaseProgress_FormItem" prop="Entity.PurchaseProgress">
									<template #label>
										<WtmLabelTooltip label="采购进度" tooltip="该明细行的采购进度状态" />
									</template>
									<el-select v-model="stateData.vmModel.Entity.PurchaseProgress" clearable class="width100">
										<el-option key="采购审批中" value="采购审批中" label="采购审批中"></el-option>
										<el-option key="采购需求池" value="采购需求池" label="采购需求池"></el-option>
										<el-option key="采购中" value="采购中" label="采购中"></el-option>
										<el-option key="运输中" value="运输中" label="运输中"></el-option>
										<el-option key="已完成" value="已完成" label="已完成"></el-option>
										<el-option key="已取消" value="已取消" label="已取消"></el-option
									></el-select>
								</el-form-item>
							</el-col> -->
					</el-row>
				</div>

				<!-- 物料信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>物料信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :span="24" class="mb20">
							<el-form-item ref="Entity_MaterialSkuId_FormItem" prop="Entity.MaterialSkuId">
								<template #label>
									<WtmLabelTooltip label="物料SKU" tooltip="采购的物料SKU" />
								</template>
								<WtmMaterialSelector
									v-model="stateData.vmModel.Entity.MaterialSkuId"
									placeholder="可选：选择已有物料SKU快速填充表单"
									label-format="{MaterialName}({MaterialCode}) - {SkuName}({SkuCode})"
									:isPurchaseScenario="true"
									:showMaterialApplyTab="true"
									:showMaterialSkuApplyTab="true"
									:showSkuListSelect="true"
								/>
							</el-form-item>
						</el-col>

						<!-- 展示已选规格信息 -->
						<el-col :span="24" class="mb20" v-if="selectedSkuInfo">
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="已选规格" tooltip="当前选择的物料规格信息" />
								</template>
								<div class="sku-info-display">
									<el-tag type="info" style="margin-right: 8px">{{ selectedSkuInfo.materialName }}</el-tag>
									<el-tag v-for="attr in selectedSkuInfo.attributes" :key="attr.id" type="success" style="margin-right: 8px">
										{{ attr.name }}: {{ attr.value }}
									</el-tag>
								</div>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IsBackupMaterial_FormItem"
								prop="Entity.IsBackupMaterial"
								:rules="[{ required: true, message: '是否备用物资为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="是否备用物资" tooltip="备用物资不计入物料呆滞考核" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.IsBackupMaterial" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 数量和金额 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>数量和金额</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="8" class="mb20">
							<el-form-item
								ref="Entity_RequestQuantity_FormItem"
								prop="Entity.RequestQuantity"
								:rules="[{ required: true, message: '申请数量为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="申请数量" tooltip="物料的申请采购数量" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.RequestQuantity" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>

						<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BudgetAmount_FormItem" prop="Entity.BudgetAmount">
								<template #label>
									<WtmLabelTooltip label="预算金额" tooltip="该物料的预算金额" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.BudgetAmount" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col> -->
					</el-row>
				</div>

				<!-- 需求说明 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>需求说明</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_RequiredArrivalDate_FormItem"
								prop="Entity.RequiredArrivalDate"
								:rules="[{ required: true, message: '要求到货日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="要求到货日期" tooltip="该物料期望的到货日期" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.RequiredArrivalDate"
									clearable
									class="width100"
									placeholder="请选择要求到货日期"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_TechnicalRequirement_FormItem" prop="Entity.TechnicalRequirement">
								<template #label>
									<WtmLabelTooltip label="技术要求" tooltip="物料的技术规格和要求说明，超过500字建议上传技术文件" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.TechnicalRequirement"
									type="textarea"
									:rows="3"
									clearable
									placeholder="请输入技术要求和规格说明"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 附件信息 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>附件信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :span="24" class="mb20">
							<el-form-item ref="SelectedFilesIds_FormItem" prop="SelectedFilesIds">
								<template #label>
									<WtmLabelTooltip label="附件" tooltip="明细行关联的附件文件，如技术文件、图纸等" />
								</template>
								<wtm-upload-file v-model="stateData.vmModel.SelectedFilesIds" clearable class="width100"></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance, watch } from 'vue';
import { SysPurchaseRequestBillEntryApi as api } from '/@/views/supplychain/syspurchaserequestbillentry/api';
import other from '/@/utils/other';
import { ISysPurchaseRequestBillEntryVm } from '/@/views/supplychain/syspurchaserequestbillentry/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 存储选中的 SKU 完整信息用于展示
const selectedSkuInfo = ref<{
	materialName: string;
	attributes: Array<{ id: string; name: string; value: string }>;
} | null>(null);

const stateData = reactive<IViewModel<ISysPurchaseRequestBillEntryVm>>({
	vmModel: {
		Entity: {
			ID: null,
			BillId: null,
			MaterialId: null,
			MaterialSkuId: null,
			IsBackupMaterial: false,
			RequestQuantity: null,
			UnitPrice: null,
			TotalAmount: null,
			BudgetAmount: null,
			TechnicalRequirement: null,
			RequiredArrivalDate: null,
			PurchaseProgress: null,
			Files: null,
		},
		SelectedFilesIds: [],
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysPurchaseRequestBills: [],
	AllSysMaterials: [],
	AllSysMaterialSkus: [],
});

// 判断BillId是否应该禁用（从主表传入时禁用）
const isBillIdDisabled = computed(() => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	return !!wtmdata?.BillId;
});

const handleApiResponse = (response: any, isSubmit = false) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};
// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other
			.getSelectList('/api/SysPurchaseRequestBillEntry/GetSysPurchaseRequestBills', [], false)
			.then((x) => (stateData.AllSysPurchaseRequestBills = x)),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => {
				other.setValue(stateData.vmModel, x);
			}),
	]);

	// 等待下一个 tick，确保 v-model 已经绑定到组件
	// 这样 WtmMaterialSelector 的 watch 能够正确触发并加载 SKU 数据
	await nextTick();
};

// 存储从主表传入的需求日期，用于同步
const needDateFromParent = ref<Date | null>(null);

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
	// 如果从主表传入了BillId，则自动填充并禁用
	if (wtmdata?.BillId) {
		stateData.vmModel.Entity.BillId = wtmdata.BillId;
	}
	// 如果从主表传入了需求日期，则自动填充到要求到货日期
	if (wtmdata?.NeedDate) {
		// 确保日期对象正确传递（处理可能的字符串或Date对象）
		let needDate: Date;
		if (wtmdata.NeedDate instanceof Date) {
			needDate = new Date(wtmdata.NeedDate.getTime());
		} else if (typeof wtmdata.NeedDate === 'string') {
			needDate = new Date(wtmdata.NeedDate);
		} else {
			needDate = new Date(wtmdata.NeedDate);
		}
		// 验证日期是否有效
		if (!isNaN(needDate.getTime())) {
			needDateFromParent.value = needDate;
			// 使用 nextTick 确保日期选择器组件已经初始化
			nextTick(() => {
				stateData.vmModel.Entity.RequiredArrivalDate = needDate;
			});
		}
	}
};

// 监听需求日期的变化，同步更新要求到货日期
watch(
	needDateFromParent,
	(newValue) => {
		if (newValue) {
			stateData.vmModel.Entity.RequiredArrivalDate = newValue;
		}
	},
	{ deep: true }
);
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		// 确保日期选择器初始化后再设置日期
		nextTick(() => {
			// 如果从主表传入了需求日期，再次确保日期正确设置
			const wtmdata = ci.attrs['wtmdata'] as any;
			if (wtmdata?.NeedDate && !stateData.vmModel.Entity.RequiredArrivalDate) {
				let needDate: Date;
				if (wtmdata.NeedDate instanceof Date) {
					needDate = new Date(wtmdata.NeedDate.getTime());
				} else if (typeof wtmdata.NeedDate === 'string') {
					needDate = new Date(wtmdata.NeedDate);
				} else {
					needDate = new Date(wtmdata.NeedDate);
				}
				if (!isNaN(needDate.getTime())) {
					stateData.vmModel.Entity.RequiredArrivalDate = needDate;
				}
			}
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
	emit('refresh');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
